package com.yyw.fileupload.util;

import net.coobird.thumbnailator.Thumbnails;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class FileUtil {

    private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);
    private static ThreadPoolUtil threadPool = ThreadPoolUtil.init();

    public static void uploadFile(byte[] file, String filePath, String fileName) throws IOException {
        checkPath(filePath);
        FileOutputStream out = new FileOutputStream(filePath + fileName);
        out.write(file);
        out.flush();
        out.close();
    }

    public static boolean isImage(InputStream inputStream) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(inputStream);
        if (bufferedImage == null) {
            return false;
        }
        return true;
    }

    public static boolean isImage(File file) throws IOException {
        BufferedImage bufferedImage = ImageIO.read(file);
        if (bufferedImage == null) {
            return false;
        }
        return true;
    }

    public static void checkPath(String dirPath) {
        checkPath(new File(dirPath));
    }

    public static void checkPath(File dirfile) {
        if (!dirfile.exists()) {
            dirfile.mkdirs();
        }
    }

    /**
     * 图片压缩
     *
     * @param file
     * @throws IOException
     */
    public static void compressFile(File file) throws IOException {
        compressFile(file, 0, 0);
    }


    /**
     * 根据文件处理图片
     *
     * @param imgFile
     * @param width
     * @param height
     * @throws IOException
     */
    public static void compressFile(File imgFile, int width, int height) throws IOException {
        compressFile(new FileInputStream(imgFile), imgFile.getParentFile().getAbsolutePath(), imgFile.getName(), width, height);
    }

    /**
     * 根据文件输入流处理图片
     *
     * @param inputStream
     * @param width
     * @param height
     * @throws IOException
     */
    public static void compressFile(InputStream inputStream, String filePath, String fileName, int width, int height) {
        checkPath(filePath);
        threadPool.executor(new Thread(() -> {
                    try {
                        Thumbnails.Builder<? extends InputStream> fileBuilder = Thumbnails.of(inputStream);
                        if (width == 0 || height == 0) {
                            fileBuilder.scale(1);
                        } else {
                            fileBuilder.size(width, height);
                        }
                        // 质量降低为原来80%
                        fileBuilder.outputQuality(0.8).toFile(filePath + fileName);
                    } catch (Exception e) {
                        logger.error("image compress failed: " + e.getMessage());
                    }
                })
        );
    }

    public static boolean imgBase64ToFile(String imgBase64Str, String filePath, String fileName) {
        imgBase64Str = imgBase64Str.substring(imgBase64Str.indexOf(",") + 1);
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(imgBase64Str);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {// 调整异常数据2w
                    b[i] += 256;
                }
            }
            uploadFile(b, filePath, fileName);
        } catch (IOException e) {
            return false;
        }
        return true;
    }

}
